package org.liaohailong.library.event;


import android.webkit.ValueCallback;

import androidx.annotation.NonNull;

import java.lang.reflect.Method;

/**
 * create by liaohailong
 * time 2022/9/22 16:34
 * desc:
 */
public class MessageEventHelper {

    /**
     * 溯源寻找所有消息订阅函数
     *
     * @param owner  消息订阅函数所在的主体
     * @param walker 发现订阅消息函数后，回调
     */
    public static void traversal(@NonNull Object owner, @NonNull ValueCallback<MessageReflectInfo> walker) {
        Class<?> clz = owner.getClass();
        // 找出所有 Subscribe 注解函数
        while (clz != null && clz != Object.class) {
            Method[] methods = clz.getDeclaredMethods();
            for (Method method : methods) {
                Subscribe annotation = method.getAnnotation(Subscribe.class);
                if (annotation != null) {
                    // 发现订阅消息的函数，收集起来
                    Class<?>[] parameterTypes = method.getParameterTypes();
                    if (parameterTypes.length != 1) {
                        // 严格要求，一个参数的函数
                        throw new IllegalArgumentException("only one param in subscribe method!");
                    }

                    Class<?> eventClz = parameterTypes[0];

                    walker.onReceiveValue(new MessageReflectInfo(owner, method, eventClz));
                }
            }
            clz = clz.getSuperclass();
        }
    }
}
